<template>
    <div>
        <el-button
            type="primary"
            @click="addProduct"
            style="margin-button: 10px"
        >
            新增商品
        </el-button>
        <el-dialog
            :title="id ? '修改商品' : '新增商品'"
            v-model="dialogVisible"
            width="400px"
            :before-close="dialogBeforeClose"
        >
            <!-- 此处需要使用子组件 -->
             <goodsEdit @success="editSuccess" :id="id" ref="goodsForm"></goodsEdit>
        </el-dialog>
        <el-table :data="tableData" style="width: 100%">
            <el-table-column prop="id" label="商品编号" width="200" />
            <el-table-column prop="name" label="商品名" width="200" />
            <el-table-column prop="price" label="价格" width="200" />
            <el-table-column label="操作">
                <template #default="{ row }">
                    <el-button type="primary" @click="editProduct(row)">
                        修改</el-button
                    >
                    <el-button type="danger" @click="deleProductItem(row.id)"
                        >删除</el-button
                    >
                </template>
            </el-table-column>
        </el-table>
    </div>
</template>

<script setup>
import {ref,onMounted} from 'vue'
import {goodsList,delGoods} from '../../api/api'
import goodsEdit from '../../components/goodsEdit.vue'
import { ElMessageBox } from 'element-plus';

const id=ref(0);
const dialogVisible=ref(false)
const tableData=ref([])
const goodsForm=ref()

onMounted(()=>{
    loadCategory()
})

const loadCategory=async()=>{
    const data=await goodsList();
    tableData.value=data
}

const deleProductItem=(id)=>{
    ElMessageBox.confirm('确定要删除吗？',{
        closeOnClickModal:false,
        confirmButtonText:'确定',
        cancelButtonText:'取消'
    }).then(async()=>{
        console.log(id)
        if(await delGoods({"id":id})){
            loadCategory()
        }
    }).catch(()=>{})
}


const addProduct=async()=>{
    if(goodsForm.value){
        goodsForm.value.resetF(0)
    }
    id.value=0;
    dialogVisible.value=true;
}

const editProduct=async(row)=>{
    if(goodsForm.value){
        goodsForm.value.resetF(row.id)
    }
    id.value=row.id;
    dialogVisible.value=true;
}

const dialogBeforeClose=()=>{
    ElMessageBox.confirm('确定关闭吗？',{
        showClose:false,
        closeOnClickModal:false,
        confirmButtonText:'确定',
        cancelButtonText:'取消'
    }).then(()=>{
        dialogVisible.value=false
    }).catch(()=>{})
}
const editSuccess=()=>{
    dialogVisible.value=false;
    loadCategory()
}

</script>